import { Card, Button, Row, Col, Statistic, Progress, Alert, Space, Switch, InputNumber, List, Tag, Divider, Modal, message, TimePicker, Form, Input, Popconfirm } from 'antd';
import { motion } from 'framer-motion';
import { Server, Play, Square, RotateCcw, Activity, Users, Globe, Clock, Settings, Power, AlertTriangle, Plus, Trash2, Share2, FileText } from 'lucide-react';
import { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/tauri';
import { listen } from '@tauri-apps/api/event';
import dayjs from 'dayjs';
import LogViewer from '../components/LogViewer';

interface AutoRestartTask {
  id: string;
  time: string;
  enabled: boolean;
  description?: string;
}

interface ServiceStatus {
  frp: 'running' | 'stopped' | 'starting' | 'stopping';
  scum: 'running' | 'stopped' | 'starting' | 'stopping';
}

const ServerControl = () => {
  const [serviceStatus, setServiceStatus] = useState<ServiceStatus>({
    frp: 'stopped',
    scum: 'stopped'
  });
  const [autoRestartTasks, setAutoRestartTasks] = useState<AutoRestartTask[]>([]);
  const [isAddingTask, setIsAddingTask] = useState(false);
  const [form] = Form.useForm();
  
  // 日志查看相关状态
  const [isViewingFrpLogs, setIsViewingFrpLogs] = useState(false);
  const [isViewingScumLogs, setIsViewingScumLogs] = useState(false);
  const [frpLogs, setFrpLogs] = useState<string[]>([]);
  const [scumLogs, setScumLogs] = useState<string[]>([]);

  // 加载服务状态和定时任务
  useEffect(() => {
    console.log('ServerControl组件初始化，开始设置事件监听器');
    loadServiceStatus();
    loadAutoRestartTasks();
    
    // 监听SCUM服务器状态变化
    const unlistenScumStatus = listen('scum_status_changed', (event) => {
      console.log('SCUM状态变化事件收到:', event.payload);
      loadServiceStatus();
    });
    
    // 监听FRP状态变化
    const unlistenFrpStatus = listen('frp_status_changed', (event) => {
      console.log('FRP状态变化事件收到:', event.payload);
      loadServiceStatus();
    });
    
    // 监听SCUM日志更新
    const unlistenScumLogs = listen('scum_log_update', (event) => {
      console.log('SCUM日志更新:', event.payload);
      const logMessage = event.payload as string;
      setScumLogs(prev => [...prev, logMessage]);
    });
    
    // 监听FRP日志更新
    const unlistenFrpLogs = listen('frp_log_update', (event) => {
      console.log('FRP日志更新:', event.payload);
      const logMessage = event.payload as string;
      setFrpLogs(prev => [...prev, logMessage]);
    });
    
    console.log('事件监听器设置完成');
    
    // 清理函数
    return () => {
      console.log('清理事件监听器');
      unlistenScumStatus.then(f => f());
      unlistenFrpStatus.then(f => f());
      unlistenScumLogs.then(f => f());
      unlistenFrpLogs.then(f => f());
    };
  }, []);

  const loadServiceStatus = async () => {
    try {
      console.log('开始加载服务状态...');
      const [frpRunning, scumRunning] = await invoke('get_service_status') as [boolean, boolean];
      console.log('服务状态加载完成:', { frpRunning, scumRunning });
      setServiceStatus({
        frp: frpRunning ? 'running' : 'stopped',
        scum: scumRunning ? 'running' : 'stopped'
      });
    } catch (error) {
      console.error('加载服务状态失败:', error);
    }
  };

  const loadAutoRestartTasks = async () => {
    try {
      console.log('开始加载定时任务...'); // 调试日志
      const tasks = await invoke('get_auto_restart_tasks') as AutoRestartTask[];
      console.log('加载到的任务:', tasks); // 调试日志
      setAutoRestartTasks(tasks || []);
    } catch (error) {
      console.error('加载定时任务失败:', error);
      setAutoRestartTasks([]);
    }
  };

  const handleFrpAction = async (action: 'start' | 'stop') => {
    try {
      if (action === 'start') {
        setServiceStatus(prev => ({ ...prev, frp: 'starting' }));
        await invoke('start_frp');
        await invoke('set_frp_running', { running: true });
        message.success('FRP 启动命令已发送');
      } else {
        setServiceStatus(prev => ({ ...prev, frp: 'stopping' }));
        await invoke('stop_frp');
        await invoke('set_frp_running', { running: false });
        message.success('FRP 停止命令已发送');
      }
      // 重新加载状态
      setTimeout(loadServiceStatus, 1000);
    } catch (error) {
      message.error(`FRP ${action === 'start' ? '启动' : '停止'}失败: ${error}`);
      setServiceStatus(prev => ({ ...prev, frp: 'stopped' }));
    }
  };

  const handleScumAction = async (action: 'start' | 'stop' | 'restart') => {
    try {
      setServiceStatus(prev => ({ 
        ...prev, 
        scum: action === 'start' ? 'starting' : action === 'stop' ? 'stopping' : 'starting' 
      }));
      
      if (action === 'start') {
        await invoke('start_scum_server');
        message.success('SCUM服务器启动命令已发送');
      } else if (action === 'stop') {
        await invoke('stop_scum_server');
        message.success('SCUM服务器停止命令已发送');
      } else if (action === 'restart') {
        await invoke('stop_scum_server');
        // 等待一段时间后重启
          try {
            await invoke('start_scum_server');
            message.success('SCUM服务器重启命令已发送');
          } catch (error) {
            message.error(`SCUM服务器重启失败: ${error}`);
            setServiceStatus(prev => ({ ...prev, scum: 'stopped' }));
          }
      }
      
      // 更新状态
      await invoke('set_scum_server_running', { 
        running: action === 'start' 
      });
      
      // 重新加载状态
      setTimeout(loadServiceStatus, 1000);
    } catch (error) {
      message.error(`SCUM服务器${action === 'start' ? '启动' : action === 'stop' ? '停止' : '重启'}失败: ${error}`);
      setServiceStatus(prev => ({ ...prev, scum: 'stopped' }));
    }
  };

  const addRestartTask = async (values: any) => {
    try {
      console.log('表单值:', values); // 调试日志
      
      if (!values.time) {
        message.error('请选择重启时间');
        return;
      }
      
      const newTask: AutoRestartTask = {
        id: Date.now().toString(),
        time: values.time.format('HH:mm'),
        enabled: true,
        description: values.description || undefined
      };
      
      console.log('添加任务:', newTask); // 调试日志
      
      const result = await invoke('add_auto_restart_task', { task: newTask });
      console.log('后端返回结果:', result); // 调试日志
      
      await loadAutoRestartTasks();
      
      setIsAddingTask(false);
      form.resetFields();
      message.success('重启任务已添加');
    } catch (error) {
      console.error('添加任务失败:', error);
      message.error(`添加任务失败: ${error}`);
    }
  };

  const removeRestartTask = async (id: string) => {
    try {
      await invoke('remove_auto_restart_task', { taskId: id });
      await loadAutoRestartTasks();
      message.success('重启任务已删除');
    } catch (error) {
      console.error('删除任务失败:', error);
      message.error('删除任务失败');
    }
  };

  const toggleTaskEnabled = async (id: string, enabled: boolean) => {
    try {
      await invoke('update_auto_restart_task', { taskId: id, enabled });
      await loadAutoRestartTasks();
      message.success(`任务已${enabled ? '启用' : '禁用'}`);
    } catch (error) {
      console.error('更新任务状态失败:', error);
      message.error('更新任务状态失败');
    }
  };

  // 查看FRP日志
  const viewFrpLogs = async () => {
    try {
      // 检查FRP是否在运行
      if (serviceStatus.frp !== 'running') {
        message.error('FRP服务未在运行，无法查看日志');
        return;
      }
      
      setIsViewingFrpLogs(true);
      
      // 获取初始日志（最近50行）
      const initialLogs = await invoke('get_frp_logs') as string[];
      setFrpLogs(initialLogs || []);
    } catch (error) {
      console.error('获取FRP日志失败:', error);
      message.error('获取FRP日志失败: ' + error);
      setIsViewingFrpLogs(false);
    }
  };

  // 查看SCUM服务器日志
  const viewScumLogs = async () => {
    try {
      // 检查SCUM服务器是否在运行
      if (serviceStatus.scum == 'stopped') {
        message.error('SCUM服务器未在运行，无法查看日志');
        return;
      }
      
      setIsViewingScumLogs(true);
      
      // 获取初始日志（最近50行）
      const initialLogs = await invoke('get_scum_logs') as string[];
      setScumLogs(initialLogs || []);
    } catch (error) {
      console.error('获取SCUM日志失败:', error);
      message.error('获取SCUM日志失败: ' + error);
      setIsViewingScumLogs(false);
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'running': return 'success';
      case 'stopped': return 'error';
      case 'starting': return 'processing';
      case 'stopping': return 'warning';
      default: return 'default';
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'running': return '运行中';
      case 'stopped': return '已停止';
      case 'starting': return '启动中';
      case 'stopping': return '停止中';
      default: return '未知';
    }
  };

  return (
    <motion.div 
      initial={{ opacity: 0, y: 20 }} 
      animate={{ opacity: 1, y: 0 }} 
      transition={{ duration: 0.6 }}
      className="space-y-6"
    >
      <div className="card-container">
        <Card className="card">
          <div className="text-center space-y-4 mb-8">
            <h1 className="text-gradient text-3xl font-bold">服务器控制面板</h1>
            <p className="text-text-secondary text-lg">管理 FRP 服务和 SCUM 服务器</p>
          </div>

          {/* 服务控制 */}
          <Row gutter={[16, 16]} className="mb-6">
            {/* FRP 服务控制 */}
            <Col xs={24} lg={12}>
              <Card 
                title={
                  <div className="flex items-center space-x-2">
                    <Share2 size={20} className="text-accent-500" />
                    <span>FRP 服务控制</span>
                    <Tag color={getStatusColor(serviceStatus.frp)}>
                      {getStatusText(serviceStatus.frp)}
                    </Tag>
                  </div>
                }
                className="card card-hover"
              >
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <span className="text-text-secondary">内网穿透服务</span>
                    <Space>
                      <Button 
                        type="primary" 
                        size="middle" 
                        className="btn-primary"
                        icon={<Play size={16} />}
                        onClick={() => handleFrpAction('start')}
                        disabled={serviceStatus.frp === 'running' || serviceStatus.frp === 'starting'}
                      >
                        启动
                      </Button>
                      <Button 
                        size="middle" 
                        className="btn-secondary"
                        icon={<Square size={16} />}
                        onClick={() => handleFrpAction('stop')}
                        disabled={serviceStatus.frp === 'stopped' || serviceStatus.frp === 'stopping'}
                      >
                        停止
                      </Button>
                      {/* <Button 
                        size="middle" 
                        className="btn-secondary"
                        icon={<FileText size={16} />}
                        onClick={viewFrpLogs}
                        disabled={serviceStatus.frp !== 'running'}
                        title={serviceStatus.frp !== 'running' ? 'FRP服务未在运行，无法查看日志' : '查看FRP日志'}
                      >
                        查看日志
                      </Button> */}
                    </Space>
                  </div>
                </div>
              </Card>
            </Col>

            {/* SCUM 服务器控制 */}
            <Col xs={24} lg={12}>
              <Card 
                title={
                  <div className="flex items-center space-x-2">
                    <Server size={20} className="text-accent-500" />
                    <span>SCUM 服务器控制</span>
                    <Tag color={getStatusColor(serviceStatus.scum)}>
                      {getStatusText(serviceStatus.scum)}
                    </Tag>
                  </div>
                }
                className="card card-hover"
              >
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <span className="text-text-secondary">游戏服务器</span>
                    <Space>
                      <Button 
                        type="primary" 
                        size="middle" 
                        className="btn-primary"
                        icon={<Play size={16} />}
                        onClick={() => handleScumAction('start')}
                        disabled={serviceStatus.scum === 'running' || serviceStatus.scum === 'starting'}
                      >
                        启动
                      </Button>
                      <Button 
                        size="middle" 
                        className="btn-secondary"
                        icon={<Square size={16} />}
                        onClick={() => handleScumAction('stop')}
                        disabled={serviceStatus.scum === 'stopped' || serviceStatus.scum === 'stopping'}
                      >
                        停止
                      </Button>
                      <Button 
                        size="middle" 
                        className="btn-secondary"
                        icon={<RotateCcw size={16} />}
                        onClick={() => handleScumAction('restart')}
                        disabled={serviceStatus.scum === 'stopped'}
                      >
                        重启
                      </Button>
                      <Button 
                        size="middle" 
                        className="btn-secondary"
                        icon={<FileText size={16} />}
                        onClick={viewScumLogs}
                        disabled={serviceStatus.scum == 'stopped'}
                        title={serviceStatus.scum == 'stopped' ? 'SCUM服务器未在运行，无法查看日志' : '查看SCUM服务器日志'}
                      >
                        查看日志
                      </Button>
                    </Space>
                  </div>
                </div>
              </Card>
            </Col>
          </Row>

          {/* 服务器统计信息 */}
          <Row gutter={[16, 16]} className="mb-6">
            <Col xs={24} sm={12} lg={6}>
              <div className="statistic-card">
                <Card className="card card-hover">
                  <Statistic
                    title="在线玩家"
                    value={12}
                    prefix={<Users size={20} className="text-accent-500" />}
                    valueStyle={{ color: '#10B981' }}
                  />
                </Card>
              </div>
            </Col>
            
            <Col xs={24} sm={12} lg={6}>
              <div className="statistic-card">
                <Card className="card card-hover">
                  <Statistic
                    title="服务器运行时间"
                    value="2天 14小时"
                    prefix={<Activity size={20} className="text-accent-500" />}
                    valueStyle={{ color: '#3B82F6' }}
                  />
                </Card>
              </div>
            </Col>
            
            <Col xs={24} sm={12} lg={6}>
              <div className="statistic-card">
                <Card className="card card-hover">
                  <Statistic
                    title="内存使用"
                    value={68}
                    suffix="%"
                    prefix={<Server size={20} className="text-accent-500" />}
                    valueStyle={{ color: '#F59E0B' }}
                  />
                  <Progress percent={68} showInfo={false} strokeColor="#F59E0B" />
                </Card>
              </div>
            </Col>
            
            <Col xs={24} sm={12} lg={6}>
              <div className="statistic-card">
                <Card className="card card-hover">
                  <Statistic
                    title="网络延迟"
                    value={45}
                    suffix="ms"
                    prefix={<Globe size={20} className="text-accent-500" />}
                    valueStyle={{ color: '#10B981' }}
                  />
                </Card>
              </div>
            </Col>
          </Row>

          {/* 自动重启设置 */}
          <div className="card-container mb-6">
            <Card 
              title={
                <div className="flex items-center space-x-2">
                  <Settings size={20} className="text-accent-500" />
                  <span>自动重启设置</span>
                </div>
              }
              className="card "
            >
              <div className="space-y-6">
                <div className="flex items-center justify-between">
                  <div className="flex items-center space-x-3">
                    <span className="text-lg font-medium">定时重启功能</span>
                  </div>
                  <Button 
                    type="primary" 
                    icon={<Plus size={16} />}
                    onClick={() => setIsAddingTask(true)}
                  >
                    添加重启时间
                  </Button>
                </div>

                {autoRestartTasks.length > 0 && (
                  <Alert
                    message="定时重启已配置"
                    description={`已配置 ${autoRestartTasks.length} 个定时重启任务`}
                    type="info"
                    showIcon
                    icon={<Clock size={16} />}
                  />
                )}
              </div>
            </Card>
          </div>

          {/* 自动重启任务列表 */}
          {autoRestartTasks.length > 0 && (
            <div className="card-container">
              <Card 
                title={
                  <div className="flex items-center space-x-2">
                    <Clock size={20} className="text-accent-500" />
                    <span>重启计划</span>
                    <Tag color="blue">{autoRestartTasks.length} 个任务</Tag>
                  </div>
                }
                className="card"
              >
                <List
                  dataSource={autoRestartTasks}
                  renderItem={(task) => (
                    <List.Item
                      actions={[
                        <Switch 
                          key="switch"
                          checked={task.enabled} 
                          onChange={(checked) => toggleTaskEnabled(task.id, checked)}
                          className="bg-gray-600"
                        />,
                        <Popconfirm
                          key="delete"
                          title="删除重启任务"
                          description="确定要删除这个重启任务吗？"
                          onConfirm={() => removeRestartTask(task.id)}
                          okText="确定"
                          cancelText="取消"
                          className="dark-popconfirm"
                          overlayClassName="dark-popconfirm-overlay"
                        >
                          <Button 
                            type="text" 
                            danger 
                            icon={<Trash2 size={16} />}
                          />
                        </Popconfirm>
                      ]}
                    >
                      <List.Item.Meta
                        avatar={
                          <div className="w-10 h-10 bg-accent-500/20 rounded-full flex items-center justify-center">
                            <Clock size={20} className="text-accent-500" />
                          </div>
                        }
                        title={
                          <div className="flex items-center space-x-3">
                            <span className="text-lg font-medium">{task.time}</span>
                            <Tag color={task.enabled ? 'success' : 'default'}>
                              {task.enabled ? '已启用' : '已禁用'}
                            </Tag>
                            {task.description && (
                              <span className="text-text-secondary text-sm">
                                {task.description}
                              </span>
                            )}
                          </div>
                        }
                        description={
                          <div className="flex items-center space-x-4">
                            <span className="text-text-secondary">定时重启任务</span>
                            {task.description && (
                              <span className="text-accent-500 font-medium">
                                {task.description}
                              </span>
                            )}
                          </div>
                        }
                      />
                    </List.Item>
                  )}
                />
              </Card>
            </div>
          )}

          {/* 添加重启任务模态框 */}
          <Modal
            title="添加重启时间"
            open={isAddingTask}
            onCancel={() => {
              setIsAddingTask(false);
              form.resetFields();
            }}
            footer={null}
          >
            <Form
              form={form}
              layout="vertical"
              onFinish={addRestartTask}
            >
              <Form.Item
                label="重启时间"
                name="time"
                rules={[{ required: true, message: '请选择重启时间' }]}
              >
                <TimePicker 
                  format="HH:mm" 
                  placeholder="选择时间"
                  className="w-full dark-timepicker"
                />
              </Form.Item>
              
              <Form.Item
                label="描述（可选）"
                name="description"
              >
                <Input 
                  placeholder="例如：每日维护重启"
                  className="bg-dark-secondary border-dark-border text-text-primary"
                />
              </Form.Item>
              
              <div className="flex justify-end space-x-2">
                <Button 
                  onClick={() => {
                    setIsAddingTask(false);
                    form.resetFields();
                  }}
                  className="btn-secondary"
                >
                  取消
                </Button>
                <Button type="primary" htmlType="submit" className="btn-primary">
                  添加
                </Button>
              </div>
            </Form>
          </Modal>

          {/* FRP日志查看模态框 */}
          <Modal
            title={
              <div className="flex items-center space-x-2">
                <FileText size={20} className="text-accent-500" />
                <span>FRP 服务日志</span>
              </div>
            }
            open={isViewingFrpLogs}
            onCancel={() => setIsViewingFrpLogs(false)}
            footer={[
              <Button key="close" onClick={() => setIsViewingFrpLogs(false)}>
                关闭
              </Button>
            ]}
            width={1000}
          >
            <LogViewer
              logs={frpLogs}
              title="FRP 实时日志"
              height={500}
              realTime={true}
              eventName="frp_log_update"
            />
          </Modal>

          {/* SCUM服务器日志查看模态框 */}
          <Modal
            title={
              <div className="flex items-center space-x-2">
                <FileText size={20} className="text-accent-500" />
                <span>SCUM 服务器日志</span>
              </div>
            }
            open={isViewingScumLogs}
            onCancel={() => setIsViewingScumLogs(false)}
            footer={[
              <Button key="close" onClick={() => setIsViewingScumLogs(false)}>
                关闭
              </Button>
            ]}
            width={1000}
          >
            <LogViewer
              logs={scumLogs}
              title="SCUM 实时日志"
              height={500}
              realTime={true}
              eventName="scum_log_update"
            />
          </Modal>
        </Card>
      </div>
    </motion.div>
  );
};

export default ServerControl; 